package androidx.gdata.spreadsheets.xml;


import org.w3c.dom.Node;

import java.util.List;

import androidx.gdata.Author;
import androidx.gdata.Category;
import androidx.gdata.Generator;
import androidx.gdata.LinkUrl;
import androidx.gdata.OpenSearch;
import androidx.gdata.spreadsheets.Spreadsheet;
import androidx.gdata.spreadsheets.SpreadsheetCollection;
import androidx.gdata.spreadsheets.Worksheet;
import androidx.gdata.spreadsheets.WorksheetEntry;
import androidx.gdata.spreadsheets.WorksheetCollection;
import androidx.gdata.xml.AuthorDeserializer;
import androidx.gdata.xml.CategoryDeserializer;
import androidx.gdata.xml.GeneratorDeserializer;
import androidx.gdata.xml.ThingWithLinksDeserializer;

public class WorksheetCollectionDeserializer extends
  ThingWithLinksDeserializer<WorksheetCollection> {
  
  private static CategoryDeserializer categoryBuilder =
    new CategoryDeserializer();
  private static AuthorDeserializer authorBuilder =
    new AuthorDeserializer();
  private static WorksheetDeserializer worksheetEntryBuilder =
    new WorksheetDeserializer();

  @Override
  public WorksheetCollection build(Node feedNode) {
   node = feedNode;
   String id = getText("id");
   String updated = getText("updated");
   String title = getText("title");
   LinkUrl[] links = getLinks();
   
   Category category = null;
   Node categoryNode = getChildNode("category");
   if (categoryNode != null) {
     category = categoryBuilder.build(categoryNode);
   }
   
   Node authorNode = getChildNode("author");
   Author author = authorBuilder.build(authorNode);
   
   String totalResults = getText("openSearch:totalResults");
   String startIndex = getText("openSearch:startIndex");
   String itemsPerPage = getText("openSearch:itemsPerPage");
   OpenSearch openSearch = new OpenSearch(totalResults, startIndex,
       itemsPerPage);
   List<Node> entryNodes = getChildNodes("entry");
   Worksheet[] entries = new Worksheet[entryNodes.size()];
   int i = 0;
   for (Node entryNode : entryNodes) {
     Worksheet entry = worksheetEntryBuilder.build(entryNode);
     entries[i++] = entry;
   }

   return new WorksheetCollection(id, updated, title,
       links, author, openSearch, entries); 
  }

}
